package com.lablzh.gdxy.service.impl;

import com.lablzh.gdxy.component.DynamicOperateExcelUtils;
import com.lablzh.gdxy.component.POIUtil;
import com.lablzh.gdxy.component.UserDetailsUtil;
import com.lablzh.gdxy.entity.*;
import com.lablzh.gdxy.entity.admin.Parameter;
import com.lablzh.gdxy.entity.practice.Practice;
import com.lablzh.gdxy.entity.practice.PracticeApply;
import com.lablzh.gdxy.entity.practice.StudentPractice;
import com.lablzh.gdxy.repository.*;
import com.lablzh.gdxy.repository.activity.ProjectRepository;
import com.lablzh.gdxy.repository.admin.ParameterRepository;
import com.lablzh.gdxy.repository.practice.PracticeApplyRepository;
import com.lablzh.gdxy.repository.practice.PracticeRepository;
import com.lablzh.gdxy.repository.practice.StudentPracticeRepository;
import com.lablzh.gdxy.service.FileService;
import com.lablzh.gdxy.service.PracticeService;
import org.apache.el.stream.Optional;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.Range;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.domain.*;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.time.LocalDate;
import java.util.*;

@Service
public class PracticeServiceImpl implements PracticeService {

    private static final String BASEPATH = "./resources/static/";
    @Autowired
    private PracticeRepository practiceRepository;
    @Autowired
    private UserDetailsUtil userDetailsUtil;
    @Autowired
    private StudentRepositoty studentRepositoty;
    @Autowired
    private PracticeApplyRepository practiceApplyRepository;
    @Autowired
    private StudentPracticeRepository studentPracticeRepository;
    @Autowired
    private POIUtil poiUtil;
    @Autowired
    private FileService fileService;
    @Autowired
    private ParameterRepository parameterRepository;
    @Autowired
    private TeacherRepository teacherRepository;
    private String confirm;


    //创建实习队
    @Override
//    @Caching(evict = {@CacheEvict(cacheNames = "practice", allEntries = true),
//            @CacheEvict(cacheNames = "teacher", allEntries = true)})
    public String createTeam(Practice practice) {
//        if(practiceRepository.findByPracticeName(practice.getPracticeName()) != null){
//            return "该生产实习已存在！";
//        }
        Parameter parameter = parameterRepository.findByCollegeAndGradeAndType(practice.getCollege(), practice.getGrade(), "生产实习");
        if (parameter == null) {
            return "教务员未设置初始互选参数";
        }
        practice.setAudit("已审核");
        practice.setStatus("关闭");
        practice.setOutlineAudit("未审");
        practice.setApplyed(0);
        practice.setRecv(0);
        practice.setSummited(0);
        practice.setToSummit(0);
        practice.setReviewed(0);
        practice.setToReview(0);
        practice.setTaskStart(parameter.getTaskStart());
        practice.setTaskDdl(parameter.getTaskDdl());
        practice.setStuChooseStart(parameter.getStuChooseStart());
        practice.setStuChooseDdl(parameter.getStuChooseDdl());
        practice.setTeaChooseStart(parameter.getTeaChooseStart());
        practice.setTeaChooseDdl(parameter.getTeaChooseDdl());
        practice.setHomeworkDdl(parameter.getHomeworkDdl());
        practice.setMaxApply(parameter.getMaxApply());
        practice.setMaxRecv(parameter.getMaxRecv());
        if (practiceRepository.save(practice) != null) {
            Teacher teacher = teacherRepository.findAllByUsername(practice.getTeacherUsername());
            if ("校内".equals(practice.getInorout())) {
                System.out.println(practice);
                System.out.println(teacher);
                teacher.setPracticeInY(teacher.getPracticeInY() + 1);
            } else {
                teacher.setPracticeOutY(teacher.getPracticeOutY() + 1);
            }
//            if(teacher.getPosition() == null){
//                teacher.setPosition("生产实习带队老师");
//            }else {
//                teacher.setPosition(teacher.getPosition()+" "+"生产实习带队老师");
//            }
            teacherRepository.save(teacher);
            return "创建成功";
        } else {
            return "创建失败";
        }
    }


    //删除实习队
    @Override
//    @Caching(evict = {@CacheEvict(cacheNames = "practice", allEntries = true),
//            @CacheEvict(cacheNames = "teacher", allEntries = true)})
    public String deleteTeam(Integer id) {
        practiceApplyRepository.deleteByProjectID(id);
        studentPracticeRepository.deleteByProjectID(id);
        Practice practice = practiceRepository.findById(id).orElse(null);
        assert practice != null;
        Teacher teacher = teacherRepository.findAllByUsername(practice.getTeacherUsername());
        //老师已出题数-1
        if (teacher != null) {
            if ("校内".equals(practice.getInorout())) {
                int temp = teacher.getPracticeInY() - 1;
                teacher.setPracticeInY(temp < 0 ? 0 : temp);
            } else {
                int temp = teacher.getPracticeOutY() - 1;
                teacher.setPracticeOutY(temp < 0 ? 0 : temp);
            }
            teacherRepository.save(teacher);
        }
        practiceRepository.deleteById(id);
        return "删除成功！";
    }

    //修改实习队
    @Override
//    @CacheEvict(cacheNames = "practice", allEntries = true)
    public String updateTeam(Practice practice) {
        practiceRepository.save(practice);
        return "修改成功！";
    }


    @Override
    public List<PracticeApply> applyListT(Integer id) {
        String username = userDetailsUtil.getUserDetails();
        return practiceApplyRepository.findAllByTeacherAndId(username, id);
    }

    @Override
    public List<PracticeApply> applyListA(Integer id) {
        return practiceApplyRepository.findAllByProjectID(id);
    }


    //获取所有实习队
    @Override
    @Cacheable(cacheNames = "practice")
    public List<Practice> getTeam() {

        return practiceRepository.findAll(Sort.by(Sort.Direction.DESC, "id"));
    }

    @Override
    public List<Practice> getTeamByTeacherUsername() {
        String username = userDetailsUtil.getUserDetails();
        return practiceRepository.findAllByTeacherUsername(username, Sort.by(Sort.Direction.DESC, "id"));
    }

    //更新实习队开放状态
    @Override
//    @CacheEvict(cacheNames = "practice", allEntries = true)
    public String updataStatus(Integer id, String status) {
        if (practiceRepository.updateStatusById(id, status) == 0) {
            return "修改失败";
        }
        return "修改成功";
    }


    @Override
//    @CacheEvict(cacheNames = "practice", allEntries = true)
    public String apply(Integer id) {
        Practice practice = practiceRepository.findById(id).orElse(null);
        assert practice != null;
        //当前时间
        LocalDate now = LocalDate.now();
        if (practice.getMaxRecv() <= practice.getRecv()) {
            return "该实习队通过人数已满，无法申请";
        }

        if (practice.getMaxApply() <= practice.getApplyed()) {
            return "选题申请已达上限";
        }
        //二轮申请
        //判断时间
        if (now.isBefore(practice.getStuChooseStart())) {
            return "选题未开始";
        }
        if (now.isAfter(practice.getStuChooseDdl())) {
            return "选题已结束";
        }
        //初始化申请表
        PracticeApply practiceApply = new PracticeApply();
        practiceApply.setProjectID(id);
        String username = userDetailsUtil.getUserDetails();
        //查询该学生选择的所有实习队
        List<PracticeApply> studentPracticeList = practiceApplyRepository.findAllByStudentUsername(username);
        //学生当前申请的实习所属类别
        String applyCategory = practice.getCategory();
        for (PracticeApply myPracticeApply : studentPracticeList) {
            if (myPracticeApply.getStatus().equals("未通过")) {
                continue;
            }
            if (practiceRepository.findById(myPracticeApply.getProjectID()).orElse(null).getCategory().equals(applyCategory)) {
                return "你已申请了其他实习队，请不要多次申请！";
            }
        }
        Student student = studentRepositoty.findAllByStID(username);
        practiceApply.setStudentUsername(student.getStID());
        practiceApply.setClasses(student.getClasses());
        practiceApply.setStudentName(student.getName());
        practiceApply.setClasses(student.getClasses());
        practiceApply.setTeacher(practice.getTeacherUsername());
        practiceApply.setPracticeName(practice.getPracticeName());
        practiceApply.setOutline(practice.getOutline());
        practiceApply.setStatus("未审");
        if (practiceApplyRepository.findByStudentUsernameAndProjectID(student.getStID(), id) != null) {
            return "请不要重复申请!";
        }
        if (practiceApplyRepository.save(practiceApply) != null) {
            practiceRepository.updateApplyedById(id, practice.getApplyed() + 1);
            if (now.isAfter(practice.getTeaChooseDdl())) {
                ddlConfirm(practiceApply.getId());
                return "已通过该实习队申请";
            }
            return "申请成功！";
        }
        return "申请失败";
    }

    public String confirmTest() {
        List<Practice> all = practiceRepository.findAll();
        for (Practice practice : all) {
            if (practice.getMaxRecv() != null && practice.getRecv() != null) {
                if (practice.getMaxRecv() <= practice.getRecv()) {
                    List<PracticeApply> allByProjectID = practiceApplyRepository.findAllByProjectID(practice.getId());
                    for (PracticeApply apply : allByProjectID) {
                        if (apply.getStatus().equals("未审")) {
                            refuse(apply.getId());
                        }
                    }
                }
            }
        }
        return "ok!!!";
    }

    @Override
    public String confirmAll(Integer id) {
        List<PracticeApply> practiceApplies = practiceApplyRepository.findAllByProjectIDAndStatus(id, "未审");
        if (practiceApplies.size() == 0) {
            return "当前学生已全部通过,请勿重复操作！";
        }
        Practice practice = practiceRepository.findById(id).orElse(null);
        if (practice.getMaxRecv() - practice.getRecv() < practiceApplies.size()) {

            return "当前申请人数" + practiceApplies.size() + "超过可以接收人数" + (practice.getMaxRecv() - practice.getRecv());
        }

        LocalDate now = LocalDate.now();
        //判断时间
        if (now.isBefore(practice.getTeaChooseStart())) {
            return "教师选择未开始";
        }
        if (now.isAfter(practice.getTeaChooseDdl())) {
            return "教师选择已结束";
        }

        assert practice != null;
        //查询对应学生信息
        for (PracticeApply practiceApply : practiceApplies) {
            Student student = studentRepositoty.findAllByStID(practiceApply.getStudentUsername());
            //判断
//            if (practice.getMaxRecv() <= practice.getRecv()) {
//                return "选题确认已达上限";
//            }
            if (practiceApplyRepository.updateStatusById(practiceApply.getId(), "已通过") == 0) {
                return "修改失败";
            }
            StudentPractice studentPractice = new StudentPractice();
            studentPractice.setProjectID(practiceApply.getProjectID());
            studentPractice.setPracticeName(practice.getPracticeName());
            studentPractice.setStudentUsername(practiceApply.getStudentUsername());
            studentPractice.setStudentName(practiceApply.getStudentName());
            studentPractice.setCollege(practice.getCollege());
            studentPractice.setMajor(student.getMajor());
            studentPractice.setClasses(practiceApply.getClasses());
            studentPractice.setGrade(practice.getGrade());
            studentPractice.setSummit("未提交");
            studentPractice.setReview("未批阅");
            studentPracticeRepository.save(studentPractice);
        }

        practiceRepository.updateRecvAndToSummitAndToReviewById(practice.getId(), practice.getRecv() + practiceApplies.size(), practice.getToSummit() + practiceApplies.size(), practice.getToReview() + practiceApplies.size());
        return "全部审核通过！";
    }

    @Override
//    @CacheEvict(cacheNames = "practice", allEntries = true)
    public String confirm(Integer id) {
        LocalDate now = LocalDate.now();
        //查询实习申请
        PracticeApply practiceApply = practiceApplyRepository.findById(id).orElse(null);
        assert practiceApply != null;
        //查询对应实习
        Practice practice = practiceRepository.findById(practiceApply.getProjectID()).orElse(null);
        assert practice != null;
        //查询对应学生信息
        Student student = studentRepositoty.findAllByStID(practiceApply.getStudentUsername());
        //判断
        if (practice.getMaxRecv() <= practice.getRecv()) {
            return "选题确认已达上限";
        }
        //判断时间
        if (now.isBefore(practice.getTeaChooseStart())) {
            return "教师选择未开始";
        }
        if (now.isAfter(practice.getTeaChooseDdl())) {
            return "教师选择已结束";
        }
        if ("已通过".equals(practiceApply.getStatus())) {
            return "已审核过!";
        }
        if (practiceApplyRepository.updateStatusById(id, "已通过") == 0) {
            return "修改失败";
        }
        StudentPractice studentPractice = new StudentPractice();
        studentPractice.setProjectID(practiceApply.getProjectID());
        studentPractice.setPracticeName(practice.getPracticeName());
        studentPractice.setStudentUsername(practiceApply.getStudentUsername());
        studentPractice.setStudentName(practiceApply.getStudentName());
        studentPractice.setCollege(practice.getCollege());
        studentPractice.setMajor(student.getMajor());
        studentPractice.setClasses(practiceApply.getClasses());
        studentPractice.setGrade(practice.getGrade());
        studentPractice.setSummit("未提交");
        studentPractice.setReview("未批阅");
        studentPracticeRepository.save(studentPractice);
        //学生和实习1：1设定
        //已确认+1,未提交+1，未批阅+1
        practiceRepository.updateRecvAndToSummitAndToReviewById(practice.getId(), practice.getRecv() + 1, practice.getToSummit() + 1, practice.getToReview() + 1);
        if (practice.getRecv() >= practice.getMaxRecv() - 1) {
            System.out.println("Recv:" + practice.getRecv() + "=====" + "Max:" + (practice.getMaxRecv() - 1));
            List<PracticeApply> allByProjectID = practiceApplyRepository.findAllByProjectID(practice.getId());
            for (PracticeApply apply : allByProjectID) {
                System.out.println("id:" + apply.getId() + "faiz_status" + apply.getStatus());
                if (apply.getStatus().equals("未审") && !apply.getId().equals(id)) {
                    System.out.println("===========");
                    System.out.println("refuse被调用！！！");
                    System.out.println("===========");
                    refuse(apply.getId());
                }
            }
        }
        return "保存成功！";
    }

    @Override
    public String ddlConfirm(Integer id) {

        //查询实习申请
        PracticeApply practiceApply = practiceApplyRepository.findById(id).orElse(null);
        assert practiceApply != null;
        //查询对饮实习
        Practice practice = practiceRepository.findById(practiceApply.getProjectID()).orElse(null);
        assert practice != null;
        //查询对应学生信息
        Student student = studentRepositoty.findAllByStID(practiceApply.getStudentUsername());
        //判断
        if ("已通过".equals(practiceApply.getStatus())) {
            return "已审核过!";
        }
        if ("未通过".equals(practiceApply.getStatus())) {
            return "没有通过!";
        }
        if (practice.getMaxRecv() <= practice.getRecv()) {
            return "选题确认已达上限";
        }
        if (practiceApplyRepository.updateStatusById(id, "已通过") == 0) {
            return "修改失败";
        }
        StudentPractice studentPractice = new StudentPractice();
        studentPractice.setProjectID(practiceApply.getProjectID());
        studentPractice.setPracticeName(practice.getPracticeName());
        studentPractice.setStudentUsername(practiceApply.getStudentUsername());
        studentPractice.setStudentName(practiceApply.getStudentName());
        studentPractice.setCollege(practice.getCollege());
        studentPractice.setMajor(student.getMajor());
        studentPractice.setClasses(practiceApply.getClasses());
        studentPractice.setGrade(practice.getGrade());
        studentPractice.setSummit("未提交");
        studentPractice.setReview("未批阅");
        studentPracticeRepository.save(studentPractice);
        //学生和实习1：1设定
        //已确认+1,未提交+1，未批阅+1
        practiceRepository.updateRecvAndToSummitAndToReviewById(practice.getId(), practice.getRecv() + 1, practice.getToSummit() + 1, practice.getToReview() + 1);
        return "保存成功！";
    }


    @Override
    public String refuse(Integer id) {
        if (practiceApplyRepository.updateStatusById(id, "未通过") == 0) {
            return "修改失败！";
        }
        PracticeApply practiceApply = practiceApplyRepository.findById(id).orElse(null);
        practiceRepository.updateApplyedById(practiceApply.getProjectID(), practiceRepository.findById(practiceApply.getProjectID()).orElse(null).getApplyed() - 1);
//        assert practiceApply != null;
//        studentPracticeRepository.deleteByProjectIDAndStudentUsername(practiceApply.getProjectID(),practiceApply.getStudentUsername());
        System.out.println("id:" + practiceApply.getId() + "======" + "删除成功");
        return "修改成功";
    }


    @Override
    public Map<String, Object> queryPerformance(StudentPractice studentPractice, int page) {
        ExampleMatcher exampleMatcher = ExampleMatcher.matching()
                .withMatcher("practiceName", ExampleMatcher.GenericPropertyMatchers.contains())
                .withMatcher("college", ExampleMatcher.GenericPropertyMatchers.contains())
                .withMatcher("grade", ExampleMatcher.GenericPropertyMatchers.contains())
                .withMatcher("major", ExampleMatcher.GenericPropertyMatchers.contains())
                .withMatcher("studentName", ExampleMatcher.GenericPropertyMatchers.contains())
                .withMatcher("classes", ExampleMatcher.GenericPropertyMatchers.contains());
        Example<StudentPractice> example = Example.of(studentPractice, exampleMatcher);
        Pageable studentPracticePage = PageRequest.of(page - 1, 20, Sort.by(Sort.Direction.DESC, "id"));
        Page<StudentPractice> all = studentPracticeRepository.findAll(example, studentPracticePage);
        Map<String, Object> data = new HashMap<>();
        data.put("totalPage", all.getTotalPages());
        data.put("total", all.getTotalElements());
        data.put("studentPractice", all.getContent());
        return data;


    }


    @Override
    public void downloadExcel(StudentPractice studentPractice1, HttpServletRequest request, String sort,HttpServletResponse response) throws FileNotFoundException {

        ExampleMatcher exampleMatcher = ExampleMatcher.matching()
                .withMatcher("practiceName", ExampleMatcher.GenericPropertyMatchers.contains())
                .withMatcher("college", ExampleMatcher.GenericPropertyMatchers.contains())
                .withMatcher("grade", ExampleMatcher.GenericPropertyMatchers.contains())
                .withMatcher("major", ExampleMatcher.GenericPropertyMatchers.contains())
                .withMatcher("studentName", ExampleMatcher.GenericPropertyMatchers.contains())
                .withMatcher("classes", ExampleMatcher.GenericPropertyMatchers.contains());
        Example<StudentPractice> example = Example.of(studentPractice1, exampleMatcher);
        List<StudentPractice>  studentPractices = studentPracticeRepository.findAll(example);

//        if ("按_系别、老师姓名_排序".equals(sort)) {
//            studentDesigns.sort(Comparator.comparing(StudentDesign::getDepartment).thenComparing(StudentDesign::getTeacherUsername));
//        } else if ("按_班级、学生学号_排序".equals(sort)) {
//            studentDesigns.sort(Comparator.comparing(StudentDesign::getClasses).thenComparing(StudentDesign::getStudentUsername));
//        }


//        if (!StringUtils.isEmpty(sort)) {
//            studentPractices = studentPracticeRepository.findAll(example, Sort.by(Sort.Direction.DESC, sort));
//        } else {
//            studentPractices = studentPracticeRepository.findAll(example);
//        }
        if (sort.equals("college")) {
            studentPractices.sort(Comparator.comparing(StudentPractice::getCollege));
        } else if (sort.equals("practiceName")) {
            studentPractices.sort(Comparator.comparing(StudentPractice::getPracticeName));
        } else if (sort.equals("studentName")) {
            studentPractices.sort(Comparator.comparing(StudentPractice::getStudentName));
        } else if (sort.equals("studentUsername")) {
            studentPractices.sort(Comparator.comparing(StudentPractice::getStudentUsername));
        } else if (sort.equals("major")) {
            studentPractices.sort(Comparator.comparing(StudentPractice::getMajor));
        } else if (sort.equals("classes")) {
            studentPractices.sort(Comparator.comparing(StudentPractice::getClasses));
        }
        DynamicOperateExcelUtils dynamicOperateExcelUtils = new DynamicOperateExcelUtils(BASEPATH + "生产实习/" + "生产实习学生汇总成绩表模板.xlsx");
        List<Map<String, Object>> datas = new ArrayList<>();
        for (StudentPractice studentPractice : studentPractices) {
            Map<String, Object> data = new HashMap<>();
            data.put("题目名称", studentPractice.getPracticeName());
            data.put("院系", studentPractice.getCollege());
            data.put("专业", studentPractice.getMajor());
            data.put("班级", studentPractice.getClasses());
            data.put("学号", studentPractice.getStudentUsername());
            data.put("姓名", studentPractice.getStudentName());
            data.put("综合评分", studentPractice.getScore());
            data.put("课堂表现成绩", studentPractice.getClassLevel());
            data.put("课堂表现评分", studentPractice.getClassScore());
            data.put("课堂表现比例", studentPractice.getClassProportion());
            data.put("作业报告成绩", studentPractice.getReportLevel());
            data.put("作业报告评分", studentPractice.getReportScore());
            data.put("作业报告比例", studentPractice.getReportProportion());
            datas.add(data);
        }
        if (!datas.isEmpty()) {
            dynamicOperateExcelUtils.appendRows(5, datas,
                    new String[]{"题目名称", "院系", "专业", "班级", "学号", "姓名", "综合评分",
                            "课堂表现成绩", "课堂表现评分", "课堂表现比例", "作业报告成绩", "作业报告评分", "作业报告比例"});
        } else {
            dynamicOperateExcelUtils.replaceCellValue(5, 0, "无相关记录");
        }
        dynamicOperateExcelUtils.exportExcel(new File(BASEPATH + "生产实习学生汇总成绩表.xlsx"));
        fileService.downloadFile("生产实习学生汇总成绩表.xlsx", request, response);
        fileService.deleteFile(BASEPATH + "生产实习学生汇总成绩表.xlsx");
    }

    @Override
    public Practice getTeamById(Integer id) {
        return practiceRepository.findById(id).orElse(null);
    }

    @Override
    public List<StudentPractice> getPracticeStudent() {
        String username = userDetailsUtil.getUserDetails();
        return studentPracticeRepository.findAllByStudentUsername(username);
    }

    @Override
    public List<PracticeApply> getPracticeApply() {
        String username = userDetailsUtil.getUserDetails();
        return practiceApplyRepository.findAllByStudentUsername(username);
    }

    @Override
    public String undo(Integer id) {
        PracticeApply practiceApply = practiceApplyRepository.findById(id).orElse(null);
        if (practiceApply == null) {
            return "不存在该申请！";
        }
        if ("已通过".equals(practiceApply.getStatus())) {
            return "该申请已通过，不能取消！";
        }
        practiceApplyRepository.deleteById(id);
        int applyed=practiceRepository.findById(practiceApply.getProjectID()).orElse(null).getApplyed();
        if("未审".equals(practiceApply.getStatus()))
        {
           applyed--;
        }
        practiceRepository.updateApplyedById(practiceApply.getProjectID(),
                applyed);
        return "删除成功！";
    }

    @Override
    public Map<String, String> addOutline(String category, Integer id, HttpServletRequest request) throws IOException {
        String username = userDetailsUtil.getUserDetails();
        Practice practice = practiceRepository.findById(id).orElse(null);
        assert practice != null;
        String teacherID = practice.getTeacherUsername();
        if (!username.equals(teacherID)) {
            Map<String, String> result = new HashMap<>();
            result.put("result", "您不是负责老师,没有该权限！");
            return result;
        }
        Map<String, String> result = fileService.summitFile(request, category, id);
        if ("上传成功！".equals(result.get("result"))) {
            practiceRepository.updateOutlineByID(id, result.get("filename"));
        }
        return result;
    }

    @Override
    public String auditOutline(Integer id, String outlineAudit) {
        practiceRepository.updateOutlineAuditByID(id, outlineAudit);
        return "审核成功！";
    }

    @Override
    public List<StudentPractice> getChoosed(Integer id) {
        return studentPracticeRepository.findAllByProjectID(id);
    }

    @Override
    public List<StudentPractice> getStudentBySummit(String summit, Integer id) {
        return studentPracticeRepository.findAllByProjectIDAndSummit(id, summit);
    }

    @Override
    public List<StudentPractice> getStudentByReview(String review, Integer id) {
        return studentPracticeRepository.findAllByProjectIDAndReview(id, review);
    }

    @Override
    public List<Practice> getPracticeByTeacher() {
        String username = userDetailsUtil.getUserDetails();
        return practiceRepository.findAllByTeacherUsername(username, Sort.by(Sort.Direction.DESC, "id"));
    }


    @Override
//    @CacheEvict(cacheNames = "practice", allEntries = true)
    public String review(Integer id, String studentUsername, Integer score, String level, String note) {
        StudentPractice studentPractice = studentPracticeRepository.findAllByProjectIDAndStudentUsername(id, studentUsername);
        if ("已批阅".equals(studentPractice.getReview())) {
            //生产实习表已批阅人数+1 未批阅-1
            Practice practice = practiceRepository.findById(id).orElse(null);
            assert practice != null;
            practiceRepository.updateToReviewAndReviewedById(id, practice.getToReview() - 1, practice.getReviewed() + 1);
        }
        studentPracticeRepository.updateReportScoreAndReportLevelAndNoteAndReviewByProjectIDAndStudentUsername(id, studentUsername, score, level, note, "已批阅");
        return "修改成功！";
    }

    @Override
//    @CacheEvict(cacheNames = "practice", allEntries = true)
    public Map<String, String> uploadReport(HttpServletRequest request, String category, Integer id) throws IOException {
        String username = userDetailsUtil.getUserDetails();
        LocalDate now = LocalDate.now();
        Map<String, String> result = fileService.summitFile(request, category, id);
        if ("上传成功！".equals(result.get("result"))) {
            //不管是第几次提交，都要更新文件名和提交时间
            studentPracticeRepository.updateReportNameAndSummitTimeByIdAndStudentUsername(id, username, result.get("filename"), now);
            StudentPractice studentPractice = studentPracticeRepository.findAllByProjectIDAndStudentUsername(id, username);
            if ("未提交".equals(studentPractice.getSummit())) {
                //学生实习表设成已提交，未批阅
                studentPracticeRepository.updateSummitAndReviewByIdAndStudentUsername(id, username, "已提交", "未批阅");
                //生产实习表 未提交-1，已提交+1
                Practice practice = practiceRepository.findById(id).orElse(null);
                assert practice != null;
                practiceRepository.updateToSummitAndSummitedAndToReviewById(id, practice.getToSummit() - 1, practice.getSummited() + 1, practice.getSummited() + 1 - practice.getReviewed());
            }
        }
        return result;
    }
}
